package com.applcn.core.handler;

import cn.hutool.core.util.StrUtil;
import com.applcn.core.base.Result;
import com.applcn.core.enums.PlatformCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常捕获工具
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获异常
     *
     * @param request
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(Exception.class)
    public Result ExceptionHandler(HttpServletRequest request, Exception exception) {
        return handleErrorInfo(request, PlatformCodeEnum.SYSTEM_ERROR.getCode(), PlatformCodeEnum.SYSTEM_ERROR.getMsg(), exception);
    }

    private Result handleErrorInfo(HttpServletRequest request, String code, String msg, Exception e) {
        log.error("系统异常", e);
        String message = e.getMessage();
        return Result.error(code, StrUtil.isBlank(message) ? msg : message);
    }
}